/**
 * Created by lycheng on 2019/8/9.
 */

const minSampleRate = 16000;
self.onmessage = function (e) {
  switch (e.data.command) {
    case 'transData': {
      const newAudioData = transform.transData(atob(e.data.data), e.data.from || 16000);
      const textstr = transform.textdata(atob(e.data.data), e.data.from || 16000);
      self.postMessage({
        command: 'newAudioData',
        data:newAudioData,
        textData:textstr
      });
      break;
    }
  }
};
var transform = {
  // 测试下载文件的
  textdata(audioDataStr){
    let newAudioData;
    const audioData = transform.strToUint8Array(audioDataStr);
    newAudioData = audioData;
    return newAudioData;
  },
  transData(audioDataStr, sampleRate) {
    let newAudioData;
    const audioData = transform.toFloat32(transform.strToUint8Array(audioDataStr));
    if (sampleRate >= minSampleRate) {
      newAudioData = audioData;
    } else {
      newAudioData = transform.changeSampleRate(audioData, sampleRate, minSampleRate);
    }
    newAudioData = audioData;
    return newAudioData;
  },
  // 16kHz → 22.05kHz 重采样
  changeSampleRate(buffer, from) {
    const data = new Float32Array(buffer);
    const fitCount = Math.round(data.length * (minSampleRate / from));
    const newData = new Float32Array(fitCount);
    const springFactor = (data.length - 1) / (fitCount - 1);
    newData[0] = data[0];
    for (let i = 1; i < fitCount - 1; i++) {
      const tmp = i * springFactor;
      const before = Math.floor(tmp);
      const after = Math.ceil(tmp);
      const atPoint = tmp - before;
      newData[i] = data[before] + (data[after] - data[before]) * atPoint;
    }
    newData[fitCount - 1] = data[data.length - 1];
    return newData;
  },

  // 转 Int16Array
  toFloat32(input) {
    const tmp = new Int16Array(input.buffer)
    const tmpData = [];
    for (let i = 0; i < tmp.length; i++) {
      const d = tmp[i] < 0 ? tmp[i] / 0x8000 : tmp[i] / 0x7fff;
      tmpData.push(d);
    }
    return new Float32Array(tmpData);
  },
  //转换成原始字节流
  strToUint8Array(rawData) {
    const outputArray = new Uint8Array(rawData.length);
    for (let i = 0; i < rawData.length; ++i) {
      outputArray[i] = rawData.charCodeAt(i);
    }
    return outputArray;
  }

};

